package cn.itcast.erp.controller;

import cn.itcast.erp.annotation.CheckPower;
import cn.itcast.erp.entity.Dep;
import cn.itcast.erp.entity.utils.AjaxResult;
import cn.itcast.erp.exception.AuthenticationException;
import cn.itcast.erp.service.DepService;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * 部门Controller类
 * @author 崔凯铭
 * @date 2019/6/5
 */

@Controller
@RequestMapping("/dep")
public class DepController {

    @Resource
    private DepService depService;

    @CheckPower("部门")
    @ResponseBody
    @RequestMapping("/insert")
    public AjaxResult insertDep(@Validated Dep dep){
        AjaxResult ar = new AjaxResult();
        this.depService.insertDep(dep);
        ar.setMsg("添加成功");
        return ar;
    }

    @CheckPower("部门")
    @ResponseBody
    @RequestMapping("/delete")
    public AjaxResult deleteDep(Long uuid){
        AjaxResult ar = new AjaxResult();
        int i = this.depService.deleteDep(uuid);
        if (i>0){
            ar.setMsg("删除成功");
        }else {
            ar.setMsg("删除失败");
        }
        return ar;
    }

    @CheckPower("部门")
    @ResponseBody
    @RequestMapping("/update")
    public AjaxResult updateDep(@Validated Dep dep){
        AjaxResult ar = new AjaxResult();
        this.depService.updateDep(dep);
        ar.setMsg("修改成功");
        return ar;
    }


    @CheckPower("部门")
    @ResponseBody
    @RequestMapping("/find")
    public AjaxResult findDep(Dep dep){
        return this.depService.findDep(dep);
    }


    @CheckPower("部门")
    @ResponseBody
    @RequestMapping("/findAllDep")
    public List<Dep> findAllDep(Dep dep){
       return depService.findAllDep (dep);
    }


    @CheckPower("部门")
    @ResponseBody
    @RequestMapping("/findById")
    public Dep findDepById(Long uuid){
        return this.depService.findDepById (uuid);
    }



    //导出Excel
    @ResponseBody
    @CheckPower("部门")
    @RequestMapping("/export")
    public void getAllDepEx(HttpServletResponse response){
        try {
            response.reset();
            response.setContentType("application/msexcel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("部门信息.xls", "UTF-8"));
            InputStream inputStream = depService.getAllDepEx();
            IOUtils.copy(inputStream,response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
